<template>
  <el-card>
    <!-- 操作工作栏 -->
    <el-row :gutter="10" class="mb8" style="margin-bottom: 5px">
      <el-col :span="1.5">
        <el-form-item>
          <el-select v-model="datasourceId"  placeholder="请选择数据源" @change="onLoadHtml">
            <el-option v-for="ds in datasourceList" :key="ds.id" :label="ds.connName" :value="ds.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleExportHtml">导出 HTML</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleExportWord">导出 Word</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleExportMarkdown">导出 Markdown</el-button>
      </el-col>
    </el-row>

    <!-- 展示文档 -->
    <div v-loading="loading" :style="'height:'+ height">
      <iframe
          :src="src"
          frameborder="no"
          style="width: 100%; height: 100%"
          scrolling="auto"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { inject, ref,onMounted } from 'vue'
import { exportHtml, exportWord, exportMarkdown} from "@/api/dbDoc";
import {useDataSourceListApi} from "@/api/datasource";
import {ElMessage} from "element-plus";


const height =  ref(document.documentElement.clientHeight - 94.5 + "px;")
const loading = ref(true)
const src = ref("")
const $download = inject('$download')
const datasourceList = ref<any>()
const datasourceId = ref<any>()

onMounted(()=>{
  setTimeout(() => {
    loading.value = false;
  }, 230);

  window.onresize = function temp() {
    height.value = document.documentElement.clientHeight - 94.5 + "px;";
  };
  getDataSourceList()
})

/*
 * @Author: zhouhx
 * @Description: 数据源
 * @Date: 2023/3/31 14:19
 */
const getDataSourceList = () => {
  useDataSourceListApi().then(res => {
    datasourceList.value = res.data
  })
}


const onLoadHtml = (datasourceId)=>{
  // 加载 Html，进行预览
  exportHtml(datasourceId).then(response => {
    let blob = new Blob([response], {type : 'text/html'});
    src.value = window.URL.createObjectURL(blob);
  })
}

/** 处理导出 HTML */
const handleExportHtml = ()=> {
  if(!datasourceId.value){
    ElMessage.warning("请选择数据源")
    return
  }
  exportHtml(datasourceId.value).then(response => {
    $download.html(response, '数据库文档.html');
  })
}
/** 处理导出 Word */
const handleExportWord = ()=> {
  if(!datasourceId.value){
    ElMessage.warning("请选择数据源")
    return
  }
  exportWord(datasourceId.value).then(response => {
    $download.word(response, '数据库文档.doc');
  })
}
/** 处理导出 Markdown */
const handleExportMarkdown = ()=> {
  if(!datasourceId.value){
    ElMessage.warning("请选择数据源")
    return
  }
  exportMarkdown(datasourceId.value).then(response => {
    $download.markdown(response, '数据库文档.md');
  })
}
</script>

<style scoped>

</style>
